<?php
namespace lib\kindEditor;

/**
 * @Auth: JH <hu@lunaz.cn>
 * Class KingEditorManager
 * @package lib\kindEditor
 */
class KingEditorManager
{
    /**
     * 根目录路径
     * @var
     */
    protected $file_path;
    /**
     * 根目录URL
     * @var
     */
    protected $file_url;

    /**
     * 允许请求读取的目录
     * @var array
     */
    protected $allow_open_folder = array('', 'image', 'flash', 'media', 'file', 'thumb');
    /**
     * 请求目录
     * @var
     */
    protected $get_dir;
    /**
     * 当前目录
     * @var
     */
    protected $current_path;
    /**
     * 输出排序
     * @var
     */
    protected $order;
    /**
     * 文件列表信息
     * @var array
     */
    protected $info = array(
        'file_list' => array()
    );

    function __construct($file_path, $file_url)
    {
        $this->file_path = $file_path;
        $this->file_url = $file_url;
        $this->get_dir = empty($_GET['dir']) ? '' : trim($_GET['dir']);
        $this->order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
        if (!in_array($this->get_dir, $this->allow_open_folder)) {
            exit('无效的目录名.');
        }
        if ($this->get_dir !== '') {
            $this->file_path = sprintf('%s/%s/', $this->file_path, $this->get_dir);
            $this->file_url = sprintf('%s/%s/', $this->file_url, $this->get_dir);
            if (!file_exists($this->file_path)) {
                //如果分类目录不存在则创建，防止打开系统根目录
                mkdir($this->file_path, 0666, true);
            }
        }
    }

    /**
     * 获取目录数据
     * @return array
     */
    function openDir()
    {
        $result = $this->buildPathInfo()->isAllowDir()->getDirFiles();
        return $result;
    }
    

    /**
     * 设置允许打开目录
     * @param $folder_name
     * @return $this
     */
    function setAllowOpenFolder($folder_name = '')
    {
        if (is_array($folder_name)) {
            $this->allow_open_folder = $folder_name;
        } elseif (is_string($folder_name)) {
            $this->allow_open_folder[] = $folder_name;
        }
        return $this;
    }

    protected function buildPathInfo()
    {
        if (empty($_GET['path'])) {
            $this->current_path = realpath($this->file_path) . '/';
            $this->info['current_url'] = $this->file_url;
            $this->info['current_dir_path'] = '';
            $this->info['moveup_dir_path'] = '';
        } else {
            $this->current_path = realpath($this->file_path) . '/' . $_GET['path'];
            $this->info['current_url'] = $this->file_url . $_GET['path'];
            $this->info['current_dir_path'] = $_GET['path'];
            $this->info['moveup_dir_path'] = preg_replace('/(.*?)[^\/]+\/$/', '$1', $this->info['current_dir_path']);
        }
        return $this;
    }

    /**
     * 检测访问目录
     */
    protected function isAllowDir()
    {
        //不允许访问到上一级目录
        if (preg_match('/\.\./', $this->current_path)) {
            exit('不允许访问.');
        }
        //最后一个字符不是  ”/“
        if (!preg_match('/\/$/', $this->current_path)) {
            exit('无效参数.');
        }
        //目录不存在或不是目录
        if (!file_exists($this->current_path) || !is_dir($this->current_path)) {
            exit('目录不存在.');
        }
        return $this;
    }

    protected function getDirFiles()
    {
        $resource = opendir($this->current_path);
        $file_list = array();
        if ($resource) {
            $i = 0;
            while (false !== ($filename = readdir($resource))) {
                if ($filename{0} == '.') {
                    continue;
                }
                $file = $this->current_path . $filename;
                if (is_dir($file)) {
                    $file_list[$i]['is_dir'] = true; //是否文件夹
                    $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件或者下级目录
                    $file_list[$i]['filesize'] = 0; //文件大小
                    $file_list[$i]['is_photo'] = false; //非图片，如果标记为图片将加载图片做缩略图
                    $file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
                } else {
                    $file_list[$i]['is_dir'] = false;
                    $file_list[$i]['has_file'] = false;
                    $file_list[$i]['filesize'] = filesize($file);
                    $file_list[$i]['dir_path'] = '';
                    $file_list[$i]['filetype'] = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    $file_list[$i]['is_photo'] = in_array(
                        $file_list[$i]['filetype'],
                        array('gif', 'jpg', 'jpeg', 'png', 'bmp')
                    );
                }
                $file_list[$i]['filename'] = $filename; //文件名，包含扩展名
                $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
                $i++;
            }
        }
        closedir($resource);
        $this->makeFilesList($file_list);
        return $this->info;
    }

    /**
     * 格式化需求的数据格式
     * @param $list
     */
    protected function makeFilesList($list)
    {
        usort($list, array($this, 'orderBy'));
        $this->info['file_list'] = $list;
        $this->info['total_count'] = count($list);
    }

    /**
     * 排序
     * @param $a
     * @param $b
     * @return int
     */
    protected function orderBy($a, $b)
    {
        if ($a['is_dir'] && !$b['is_dir']) {
            return -1;
        } else {
            if (!$a['is_dir'] && $b['is_dir']) {
                return 1;
            } else {
                if ($this->order == 'size') {
                    if ($a['filesize'] > $b['filesize']) {
                        return 1;
                    } else {
                        if ($a['filesize'] < $b['filesize']) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                } else {
                    if ($this->order == 'type') {
                        return strcmp($a['filetype'], $b['filetype']);
                    } else {
                        return strcmp($a['filename'], $b['filename']);
                    }
                }
            }
        }
    }

}
